package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.constant.ImgCodeConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.vo.SmsVo;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.CodeGenerateUtils;
import cn.itsource.ymcc.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public JsonResult createImageCode(String key) {
        //2.图形验证码 糊涂工具包
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(ImgCodeConstants.IMG_CODE_WIDTH,
                ImgCodeConstants.IMG_CODE_HEIGHT,
                ImgCodeConstants.IMG_CODE_COUNT,
                ImgCodeConstants.IMG_CODE_THICKNESS);
        //验证码
        String code = captcha.getCode();
        //图片验证码
        String imageBase64 = captcha.getImageBase64();
        //保存到redis里面
        redisTemplate.opsForValue().set(ImgCodeConstants.IMG_CODE_REGISTER_KEY + key,code,
                ImgCodeConstants.IMG_CODE_OVER_TIME, TimeUnit.MINUTES);
        return JsonResult.success().setData(imageBase64);
    }

    @Override
    public JsonResult sendSmsCode(SmsVo smsVo) {
        String key =  ImgCodeConstants.IMG_CODE_REGISTER_KEY + smsVo.getImageKey();
        AssertUtil.isTrue(redisTemplate.hasKey(key),"图片验证已过期");

        String code = redisTemplate.opsForValue().get(key).toString();
        AssertUtil.isTrue(code.equalsIgnoreCase(smsVo.getImageCode()),"图片验证码输入错误");

        //发送短信验证码
        String phoneCode = StrUtils.getRandomString(RConst.Num.INT_6);
        String phoneValue  = null;

        //手机验证码的key
        String phoneKey = ImgCodeConstants.IMG_CODE_REGISTER_PHONE_KEY + smsVo.getPhone();
        Long expire = redisTemplate.getExpire(phoneKey, TimeUnit.SECONDS);//得到剩余时间     360
        //特殊功能
        if(expire>300){
            throw new GlobalException("你太快了，慢点！");//防止用户在1分钟之内多次点击
        }

        if(expire > 180){
            phoneValue = redisTemplate.opsForValue().get(phoneKey).toString();
        }else {
            phoneValue = phoneCode;
            //保存redis
            redisTemplate.opsForValue().set(ImgCodeConstants.IMG_CODE_REGISTER_PHONE_KEY + smsVo.getPhone(),phoneCode,
                    ImgCodeConstants.IMG_CODE_OVER_TIME, TimeUnit.MINUTES);
        }

        System.out.println("发送"+smsVo.getPhone()+"验证码:"+phoneValue);
        return JsonResult.success();
    }
}
